在 APP 开发过程中经常会使用到 UIViewController
来展示视图,在应用展示过程中经常会使用到 UIViewController
视图控制器件进行跳转。
下面小编将会介绍在视图控制间进行跳转和传递数据。
跳转方式
视图实现跳转方式:
UIViewController
实现跳转UINavigationController
实现跳转UITabBarController
实现跳转Segue
实现跳转
UIViewController
实现跳转
(1)实现跳转到下一个界面
1 | - (void)presentViewController:(UIViewController *)viewControllerToPresent animated: (BOOL)flag completion:(void (^ __nullable)(void))completion NS_AVAILABLE_IOS(5_0); |
跳转具体实现:
1 | SecondViewController *secondVC = [[SecondViewController alloc] init]; |
(2)返回上一个界面
1 | - (void)dismissViewControllerAnimated: (BOOL)flag completion: (void (^ __nullable)(void))completion NS_AVAILABLE_IOS(5_0); |
返回上一个界面具体实现:
1 | - (void)dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion { |
UINavigationController
实现跳转
如果当前 UIViewController
在 UINavigationController
管理中,可以使用 UINavigationController
来进行相关的界面跳转。
UINavigationController
基本知识
UINavigationController
是一个 navigation stack
的堆栈,来进行管理其中 UIViewController
来进行展示。
A navigation controller object manages the currently displayed screens using the navigation stack, which is represented by an array of view controllers. //来自官方文档
下图是 navigation stack
来管理 UIViewController
视图控制器。
下图是使用 revel
展示 UINavigationController
和 UIViewController
之间的视图关系。
UINavigationController
实现界面跳转
(1)UINavigationController
界面跳转 API
1 | - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated;//把当前 ViewController 压入 stack,跳转到下一个 试图控制器 |
(2)视图跳转代码实现:
1 | [self.navigationController pushViewController:secondVC animated:YES]; |
UITabBarController
实现跳转
使用 UITabBarController
的 tab
来实现 UIViewController
视图控制器之间进行跳转。
下图是关于 UITabBarController
在视图上面展示:
下图列出revel
展示 UIViewController
和 UITabBarController
层次展示:
Segue
实现跳转
多出现于UIStoryboard中,是不同类之间跳转的一根线。换种说法就是:Storyboard上每一根用来界面跳转的线,都是一个UIStoryboardSegue对象(简称Segue)
跳转具体如下:
- 实现原理
在 - (void)performSegueWithIdentifier:(NSString *)identifier sender:(id)sender
方法中在创建segue
对象,并且设置segue
对象里面的属性,来源,目的。具体步骤为:
(1)根据定义好的标识(identifier)
去storyboard
中查找,有木有这跟线。如果有,就创建segue
对象;
(2)设置segue
的来源控制器 :segue. source = self
;
(3)创建segue
的目的控制器对象,并且设置为segue
的目的控制器;
(4)- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
方法中具体实现跳转功能。可以在这个方法中获取将要跳转到的控制器(segue.destinationViewController)
,并进行值传递。
Segue
实现的API
1 | + (instancetype)segueWithIdentifier:(nullable NSString *)identifier source:(UIViewController *)source destination:(UIViewController *)destination performHandler:(void (^)(void))performHandler NS_AVAILABLE_IOS(6_0); |